package com.robot.controller;

import com.robot.common.api.CurrentUserSupport;
import com.robot.common.result.PageResult;
import com.robot.common.result.Response;
import com.robot.dao.dto.BulkFileDTO;
import com.robot.dao.dto.BulkfilePageQueryDTO;
import com.robot.dao.entity.BulkFile;
import com.robot.dao.vo.FileOverViewVO;
import com.robot.service.BulkFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
@RestController
@RequestMapping("/file")
@Slf4j
@Api(tags = "批量文件相关接口")
public class BulkFileController {

    @Autowired
    private BulkFileService bulkFileService;
    @Autowired
    private CurrentUserSupport currentUserSupport;
    @PostMapping("/bulkuupload")
    @ApiOperation(value = "上传批量回答文件")
    public Response uploadbulkfile(@RequestParam("userId") String userId,
                                   @RequestParam("robotId") String robotId,
                                   @RequestParam("knowledgeId") String knowledgeId,
                                   @RequestParam("minioBucketName") String minioBucketName,
                                   @RequestParam("files") MultipartFile[] files
    ){

        for(MultipartFile file : files){
            if (ObjectUtils.isEmpty(file) || file.getSize() <= 0) {
                return Response.error("文件为空");
            }
        }
        BulkFileDTO bulkFileDTO = new BulkFileDTO();
        bulkFileDTO.setUserId(userId);
        bulkFileDTO.setRobotId(robotId);
        bulkFileDTO.setFiles(files);
        bulkFileDTO.setKnowledgeId(knowledgeId);
        bulkFileDTO.setMinioBucketName(minioBucketName);
        List<FileOverViewVO> upload;
        try {
            upload = bulkFileService.uploadBulkFile(bulkFileDTO);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Response.success(upload);
    }

    @PostMapping("/bulkAnswer")
    @ApiOperation(value = "chatgpt批量回答问题")
    public Response bulkanswerfile(@RequestBody BulkFileDTO bulkFileDTO)
    {

        BulkFile bulkFile = bulkFileService.findFileByIds(bulkFileDTO.getFileId(), bulkFileDTO.getRobotId(), String.valueOf(currentUserSupport.getCurrentUserId()));
        if (bulkFile != null) {
            try {
                // 根据文件路径或URL读取文件并转换为 MultipartFile
                InputStream inputStream = new URL(bulkFile.getFileUrl()).openStream();
                MultipartFile multipartFile = new MockMultipartFile(
                        "file",
                        bulkFile.getFileName(),
                        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        inputStream
                );
                String uniqueFileName = bulkFileService.processFile(bulkFile,multipartFile);
                return Response.success("文件正在处理... 任务ID: " + uniqueFileName);
            } catch (IOException e) {
                e.printStackTrace();
                return Response.success("文件处理失败");
            }
        } else {
            // 如果没有找到文件，返回错误信息
            return Response.success("文件未找到");
        }
    }

    @PostMapping("/stopAnswering")
    @ApiOperation(value = "中断批量回答问题")
    public Response stopanswering(@RequestBody BulkFileDTO bulkFileDTO){
        boolean success = bulkFileService.stopTask(bulkFileDTO.getFileId());
        if (success){
            return Response.success("中断成功");
        }else{
            return Response.success("任务已完成");
        }
    }

    @PostMapping("/pageQuerybulkfileByUserId")
    @ApiOperation(value = "分页查询批量文件")
    public Response<PageResult> pageQuerybulkfileByRobotId(@RequestBody BulkfilePageQueryDTO bulkfilePageQueryDTO){
        PageResult pageResult = bulkFileService.pageQueryfile(bulkfilePageQueryDTO);
        return Response.success(pageResult);
    }

}
